package com.xt.base.service;

import java.util.Date;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;

import com.xt.base.acegi.UserDetailsImpl;
import com.xt.base.dao.hibernate.BaseDaoHibernate;
import com.xt.base.dao.hibernate.UserDaoHibernate;
import com.xt.base.dao.hibernate.code.AffairParameter;
import com.xt.base.model.base.LoginLog;
import com.xt.base.model.system.Role;
import com.xt.base.model.system.User;

public class LoginService extends BaseService implements UserDetailsService {
	private static final long serialVersionUID = 2072085709730210073L;
	private UserDaoHibernate userDAO;
	
	public User reLoadUserInfo(String username,String password){
		User user = userDAO.getLoginUser(username);
		user.initialize();
		this.saveLoginLog(user);
		return user;
	}
	

	public void saveLoginLog(User user){
		LoginLog log = new LoginLog();
		log.setLoginDate(new Date());
		log.setUser(user);
		userDAO.save(log);
	}

	public UserDetails loadUserByUsername(String loginName)
			throws UsernameNotFoundException, DataAccessException {
		User user = userDAO.getLoginUser(loginName);
		if (user == null) {
			throw new UsernameNotFoundException("用户没有找到: " + loginName);
		}
		GrantedAuthority[] arrayAuths = null;
		int rSize = user.getRoles().size(), i = 0;
		if (rSize == 0)
			throw new UsernameNotFoundException(" user: " + loginName
					+ "没有定义任何角色");
		arrayAuths = new GrantedAuthority[rSize];
		for (Role r : user.getRoles()) {
			arrayAuths[i] = new GrantedAuthorityImpl(r.getAcegiName());
			i++;
		}
		this.saveLoginLog(user);
		// 检查是否使用加密锁
		if (AffairParameter.getInstance().isUseLock()) {
			return new UserDetailsImpl(user.getUsername(),
					user.getPassword() == null ? "" : user.getPassword(), true,
					true, true, true, arrayAuths, user.getLockedId());
		} else {
			return new UserDetailsImpl(user.getUsername(), user
					.getNoEncryptLockpassword() == null ? "" : user
					.getNoEncryptLockpassword(), true, true, true, true,
					arrayAuths, null);
		}
	}
	
	@Override
	public BaseDaoHibernate getDao() {
		return userDAO;
	}

	public void setUserDAO(UserDaoHibernate userDAO) {
		this.userDAO = userDAO;
	}

}
